package com.dbappsecurity.jsbridge.receivers;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.dbappsecurity.jsbridge.webview.CompletionHandler;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;

/**
 * Created by Arirus on 2017/8/9.
 */

public class NetworkChangeReceiver extends BroadcastReceiver {
  private CompletionHandler mHandler;

  public NetworkChangeReceiver(CompletionHandler handler) {
    mHandler = handler;
  }

  @Override
  public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
      ConnectivityManager connectivityManager = (ConnectivityManager) context
          .getSystemService(Context.CONNECTIVITY_SERVICE);

      NetworkInfo activeNetworkInfo = connectivityManager
          .getActiveNetworkInfo();
      Map<String, String> map = new HashMap<>();
      map.put("type", "none");
      if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {

        if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) {
          map.put("type", "wifi");
        } else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) {
          map.put("type", "mobile");
        }
      } else {
        map.put("type", "none");
      }
      JSONObject jsonObject = new JSONObject(map);

      mHandler.setProgressData(jsonObject.toString());
    }
  }
}
